/**
 * 
 */
package gui.workspace;

import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import model.Model;

/**
 * @author Troy Ferrell
 * @author David Colon-Smith
 */

public class Workspace extends JTabbedPane
{
	private Model myModel;
	private static final String TAB_NAME = "New Tab"; 
	Collection<WorkspaceEditor> myEditors;
	private String copyText = "";
	
	public Workspace(Model newModel)
	{
		myModel = newModel;
		myEditors = new ArrayList<WorkspaceEditor>();
		addNewTabButton();
		addTab();
	}
	
	/**
	 * Add new tab to the system with no name or preloaded data
	 */
	public void addTab()
	{
		this.addTab(TAB_NAME, "");
	}
	
	/**
	 * Add new tab to workspace with tab name and preloaded data
	 * 
	 * @param tabName
	 * @param data
	 */
	public void addTab(String tabName, String data)
	{	
		WorkspaceEditor editor = new WorkspaceEditor(data);
		myEditors.add(editor);
		
		this.addTab(TAB_NAME, editor);
		this.setTabComponentAt(this.getTabCount() - 1, new WorkspaceTab(this, TAB_NAME));
		
		this.setSelectedIndex(myEditors.size());
		setVisible(true);
	}
	
	/**
	 * Special tab button that only has add button in tab with no content
	 * - used by user to create new tabs
	 */
	public void addNewTabButton()
	{
		this.addTab(null,
				new JPanel());
		JButton newTabButton = new JButton(" + ");
		newTabButton.setMargin(new Insets(0, 0, 0, 0));

		ActionListener al;
		al = new ActionListener()
		{
			public void actionPerformed(ActionEvent ae)
			{
				addTab();
			}
		};
		newTabButton.addActionListener(al);

		this.setTabComponentAt(this.getTabCount() - 1, newTabButton);
		this.setSelectedIndex(this.getTabCount() - 2);
		setVisible(true);
	}
	
	/**
	 * Close button from tab was pressed...removes a tab from the workspace
	 * @param index
	 */
	public void removeTab(int index)
	{
		myEditors.remove(getComponentAt(index));
		System.out.println(myEditors.size());
		this.remove(index);
		
		// TODO: check to see if file was saved than prompt user if still ok to close
	}
	
	/**
	 * Get current workspace editor that is open
	 * 
	 * @return the editor
	 */
	public WorkspaceEditor getSelectedEditor()
	{
		return (WorkspaceEditor)this.getSelectedComponent();
	}
	
	/**
	 * Get selected text and store in copy data
	 */
	public void copyText()
	{
		WorkspaceEditor editor = (WorkspaceEditor)this.getSelectedComponent();
		if(editor == null)
			return;
		
		copyText = editor.getSelectedText();
	}
	
	/**
	 * paste copy data at caret of current editor
	 */
	public void pasteText()
	{
		WorkspaceEditor editor = (WorkspaceEditor)this.getSelectedComponent();
		if(editor == null)
			return;
		
		editor.insertTextAtCaret(copyText);
	}
}
